<?php
/**
 * 金蝶星空云 webapi
 *
 * php实现金蝶星空云webapi相关的接口
 * @author: yanxs <541139655@qq.com>
 * @version: 1.0
 * @date: 2021/3/15
 */

namespace App\Services\Outer\Kingdee;

use Illuminate\Support\Facades\Redis;
use App\Exceptions\CommonException;

class Webapi
{
    protected $cookieJar; //cookie存储地址
    protected $loginParams;
    protected $apiUrl;
    public function __construct()
    {
        $this->cookieJar = env("KD_WEB_API_COOKIEJAR");
        $this->apiUrl    = env("KD_WEB_API_URL");
        $this->loginParams = [
            env("KD_WEB_API_ACCTID"),
            env("KD_WEB_API_USER"),
            env("KD_WEB_API_PWD"),
            env("KD_WEB_API_ICID"),
        ];
    }

    /**
     * 接口登录
     * @param false $is_retry 是否重试
     * @return false
     */
    public function login($is_retry = false)
    {
        $loginUrl = $this->apiUrl.'Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc';

        $cookeTime = Redis::get("cooke_time");
        //每20分钟重新请求一次或者强制重置
        if(empty($cookeTime) || $is_retry) {
            $postContent = $this->createPostdata($this->loginParams);
            $res = $this->invokePost($loginUrl,$postContent,$this->cookieJar,true);
            $loginInfo = json_decode($res, true);
            if ($loginInfo['LoginResultType'] == 1) {
                Redis::setex("cooke_time",20*60, time());
                return $loginInfo;
            } else {
                return false;
            }
        }
    }

    /**
     * 查看接口
     * @param $data
     */
    public function view($data)
    {
        $viewUrl = $this->apiUrl.'Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc';
        $arrRes = $this->requestApi($viewUrl, $data);

        if (!empty($arrRes['Result']['ResponseStatus'])) {
            //return false;
            throw new CommonException( $arrRes['Result']['ResponseStatus']['Errors'][0]['Message'], "00003");
        } else {
            return $arrRes['Result']['Result'];
        }
    }

    /**
     * 表记录查询
     * @param $data
     */
    public function billQuery($data)
    {
        $queryUrl = $this->apiUrl.'Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc';
        $arrRes = $this->requestApi($queryUrl, $data);
        if (!empty($arrRes['Result']['ResponseStatus'])) {
            //return false;
            throw new CommonException( $arrRes['Result']['ResponseStatus']['Errors'][0]['Message'], "00003");
        } else {
            return $arrRes;
        }
    }

    public function businessQuery($data)
    {
        $queryUrl = $this->apiUrl.'Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.QueryBusinessInfo.common.kdsvc';
        $arrRes = $this->requestApi($queryUrl, $data);
        dd($arrRes);
    }

    /**
     * 保存数据(添加/修改)
     * @param $data
     * @return mixed
     * @throws CommonException
     */
    public function save($data)
    {
        $saveUrl = $this->apiUrl.'Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc';
        $arrRes = $this->requestApi($saveUrl, $data);

        if (!empty($arrRes['Result']['ResponseStatus']['Errors'])) {
            //return false;
            throw new CommonException( $arrRes['Result']['ResponseStatus']['Errors'][0]['Message'], "00003");
        } else {
            return $arrRes['Result']['ResponseStatus']['SuccessEntitys'];
        }
    }

    /**
     * 提交保存的数据,数据状态变为审核中
     * @param $data
     */
    public function submit($data)
    {
        $submitUrl = $this->apiUrl.'Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc';
        $arrRes = $this->requestApi($submitUrl, $data);
        if (!empty($arrRes['Result']['ResponseStatus']['Errors'])) {
            //return false;
            throw new CommonException( $arrRes['Result']['ResponseStatus']['Errors'][0]['Message'], "00003");
        } else {
            return $arrRes['Result']['ResponseStatus']['SuccessEntitys'];
        }
    }

    /**
     * 数据审核，由审核中变为已经审核
     * @param $data
     */
    public function audit($data)
    {
        $auditUrl = $this->apiUrl.'Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc';
        $arrRes = $this->requestApi($auditUrl, $data);
        if (!empty($arrRes['Result']['ResponseStatus']['Errors'])) {
            //return false;
            throw new CommonException( $arrRes['Result']['ResponseStatus']['Errors'][0]['Message'], "00003");
        } else {
            return $arrRes['Result']['ResponseStatus']['SuccessEntitys'];
        }
    }

    /**
     * 数据反审核 ,由审核变为重新审核状态
     * @param $data
     */
    public function unAudit($data)
    {
        $unAuditUrl = $this->apiUrl.'Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc';
        $arrRes = $this->requestApi($unAuditUrl, $data);
        if (!empty($arrRes['Result']['ResponseStatus']['Errors'])) {
            //return false;
            throw new CommonException( $arrRes['Result']['ResponseStatus']['Errors'][0]['Message'], "00003");
        } else {
            return $arrRes['Result']['ResponseStatus']['SuccessEntitys'];
        }
    }

    /**
     * 封装请求api逻辑
     * @param $url
     * @param $data
     */
    protected function requestApi($url, $data)
    {
        //先登录
        $isLogin = $this->login();
        if (empty($isLogin)) {
            //强制重新登录一次
            $this->login(true);
        }
        $postContent = $this->createPostdata($data);
        $res = $this->invokePost($url,$postContent,$this->cookieJar,false);
        $arrRes = json_decode($res, true);
        return $arrRes;
    }
    /**
     * 请求api
     * @param $url
     * @param $post_content
     * @param $cookie_jar
     * @param $isLogin
     * @return mixed
     */
    protected function invokePost($url,$post_content,$cookie_jar,$isLogin)
    {
        $ch = curl_init($url);

        $this_header = array(
            'Content-Type: application/json',
            'Content-Length: '.strlen($post_content)
        );

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_content);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if($isLogin){
            curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);
        }
        else{
            curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

    /**
     * 构造Web API请求格式
     * @param $args
     * @return mixed
     */
    protected function createPostdata($args) {
        $postdata = array(
            'format'=>1,
            'useragent'=>'ApiClient',
            'rid'=>$this->createGuid(),
            'parameters'=>$args,
            'timestamp'=>date('Y-m-d'),
            'v'=>'1.0'
        );

        return json_encode($postdata);
    }

    /**
     * 构造rid
     * @return string
     */
    protected function createGuid() {
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = chr(123)// "{"
            .substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,20,12)
            .chr(125);// "}"
        return $uuid;
    }
}
